﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Web;

namespace Turners.DMS.WebParts
{
    public partial class PdfDocViewerUserControl : UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string pdfDocumentPath = string.Empty;
            string id = HttpContext.Current.Request["ID"];
            int listId;
            bool isValidId = Int32.TryParse(id, out listId);
            if (isValidId)
            {
                pdfDocumentPath = GetPDFDocumentName(listId);
                this.pdfHolder.InnerHtml = string.Format("<embed src=\"{0}\" type=\"application/pdf\" width=\"90%\"height=\"800\" />", pdfDocumentPath);
            }
            else
            {
                this.pdfHolder.InnerText = "Invalid Paramters: No PDF displayed";
            }
        }
        private string GetPDFDocumentName(int listId)
        {
            string pdfFullPath = string.Empty;
            //string siteUrl = ConfigurationManager.AppSettings["SiteUrl"]; 
            //string webUrl = ConfigurationManager.AppSettings["WebUrl"];
            //string docStoreName = ConfigurationManager.AppSettings["DocStore"];

            string fullPath = HttpContext.Current.Request.Url.ToString();
            string docStoreName = "DocumentStore";
            int index = fullPath.IndexOf(docStoreName);
            string siteUrl = fullPath.Substring(0, index-1);
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList documentStore = web.Lists[docStoreName];
                    SPListItem document = documentStore.GetItemById(listId);
                    string webUrl = web.Url;
                    if (document != null)
                    {
                        string pdfName = document.Name;
                        pdfFullPath = String.Format("{0}/{1}/{2}", webUrl, docStoreName, pdfName);
                    }
                }
            }
            return pdfFullPath;
        }
    }
}
